

//
//  CloudDiskController.m
//  gdemm
//
//  Created by 乔明超 on 16/9/20.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "CloudDiskController.h"
#import "CloudTableViewCell.h"
#import "InboxManager.h"
#import "DocManager.h"
#import "Utils.h"
#import "ApiSupport.h"
#import "FileUtil.h"
#import "FileInfo.h"
#import "ToastManager.h"
#import "DocManager.h"
#import "MJRefresh.h"
#import "CustomButton.h"
#import "Masonry.h"
#import "MJRefresh.h"
#import "SVProgressHUD.h"
#import "CADViewer.h"
#import "UITabBar+RedDotBadge.h"
#import "UIAlertController+alert.h"
#define DEVICEVERSION     [[[UIDevice currentDevice] systemVersion] floatValue]
@interface CloudDiskController ()
@property (strong,nonatomic) NSMutableArray<FileInfo *> *fileListArray;
@property (strong,nonatomic) CustomButton *mBtnCrush;
@property (strong,nonatomic) CustomButton *mBtnDelete;
@property(nonatomic,strong)UIView *coverView;
@property(nonatomic,strong) NSOperationQueue * queue;
@property(nonatomic,assign)BOOL redFlag;
@end
static NSString * const identifier = @"filelist";
@implementation CloudDiskController

#pragma mark - 懒加载
-(UIView *)coverView{
    if (_coverView == nil) {
        _coverView = [[UIView alloc]initWithFrame:CGRectMake(0, WINDOWHEIGHT-176-49, WINDOWWIDTH, 176)];
        _coverView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
        
        [_coverView addSubview:self.mBtnDelete];
        [_coverView addSubview:self.mBtnCrush];
        
        self.mBtnDelete.x = _coverView.centerX +42;
        self.mBtnDelete.y = 10;
        self.mBtnCrush.x = _coverView.centerX -42-17;
        self.mBtnCrush.y = 10;
        if (![DeviceTypeJudge isPadDeviceType]) {
            _coverView.frame = CGRectMake(0, WINDOWHEIGHT-150*KHeightScale, WINDOWWIDTH, 101*KHeightScale);
            self.mBtnDelete.y = 30;
            self.mBtnCrush.y = 30;
        }
    }
    return _coverView;
}
//添加粉碎按钮
- (CustomButton *)mBtnCrush{
    if (_mBtnCrush == nil) {
        _mBtnCrush = [CustomButton buttonWithType:UIButtonTypeSystem];
        [_mBtnCrush setImage:[[Utils imageWithKey:@"other_icon_crush"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] forState:UIControlStateNormal];
        [_mBtnCrush setTitle:NSLocalizedString(@"str_crushing", @"粉碎") forState:UIControlStateNormal];
        [_mBtnCrush addTarget:self action:@selector(crushHandler:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _mBtnCrush;
}


//添加删除按钮
- (CustomButton *)mBtnDelete{
    if (_mBtnDelete == nil) {
        _mBtnDelete = [CustomButton buttonWithType:UIButtonTypeSystem];
        [_mBtnDelete setImage:[[Utils imageWithKey:@"other_icon_delete"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] forState:UIControlStateNormal];
        [_mBtnDelete setTitle:NSLocalizedString(@"str_delete", @"删除") forState:UIControlStateNormal];
        [_mBtnDelete addTarget:self action:@selector(crushHandler:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _mBtnDelete;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(skinSwitchHandler) name:@"skinswitch" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadCloudData) name:@"cloudReloadData" object:nil];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editBarButtonItemHnadler)];
    
    [self setupTableView];
    __weak __typeof(self) weakSelf = self;
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [[InboxManager getInstance]reloadFileInfo];
        weakSelf.fileListArray = [InboxManager getInstance].mfiles;
        if ([weakSelf.navigationItem.title isEqualToString: NSLocalizedString(@"str_multi_select", @"多选")]) {
            for (FileInfo *fileInfo in self.fileListArray) {
                fileInfo.selState = YES;
            }
        }
        [weakSelf  cancelBarButtonItemHnadler];
        [weakSelf reloadCloudData];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}
-(void)reloadCloudData{
    
    NSBlockOperation * reloadDataOperation  = [NSBlockOperation blockOperationWithBlock:^{
        [self.tableView reloadData];
    } ];
    NSBlockOperation * addRedflagOperation = [NSBlockOperation blockOperationWithBlock:^{
        self.redFlag = NO;
        [self.fileListArray enumerateObjectsUsingBlock:^(FileInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (!obj.localExist) {
                self.redFlag = YES;
                *stop  = YES;
            }
        }];
        if (self.redFlag) {
            [self.tabBarController.tabBar showBadgeOnItemIndex:2];
        }else{
            [self.tabBarController.tabBar hideBadgeOnItemIndex:2];
        }
    } ];
    
    [addRedflagOperation addDependency:reloadDataOperation];
    
    self.queue = [NSOperationQueue mainQueue];
    [self.queue addOperation:reloadDataOperation];
    [self.queue addOperation:addRedflagOperation];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:[DeviceTypeJudge getTitleFont]]} forState:UIControlStateNormal];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self cancelBarButtonItemHnadler];
}
#pragma mark - 初始化tableView
- (void)setupTableView{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadFileInfo];
    });
}
#pragma mark - 加载信息并刷新列表
- (void)loadFileInfo{
    [[InboxManager getInstance]reloadFileInfo];
    self.fileListArray = [InboxManager getInstance].mfiles;
    [self reloadCloudData];
}
#pragma mark - navigationBar右侧点击事件
- (void)editBarButtonItemHnadler{
    if (self.fileListArray.count == 0) {
        [self.view makeToast:NSLocalizedString(@"str_noOperationalFiles", @"当前没有可操作文件")];
        return;
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelBarButtonItemHnadler)];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:[DeviceTypeJudge getTitleFont]]} forState:UIControlStateNormal];
    self.navigationItem.title = NSLocalizedString(@"str_multi_select", @"多选");
    for (FileInfo *fileInfo in self.fileListArray) {
        fileInfo.selState = YES;
    }
    [self.tabBarController.view addSubview:self.coverView];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 176+49, 0);
    //self.tableView.mj_header.hidden = YES;
    [self reloadCloudData];
}

- (void)cancelBarButtonItemHnadler{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editBarButtonItemHnadler)];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:[DeviceTypeJudge getTitleFont]]} forState:UIControlStateNormal];
    self.navigationItem.title = NSLocalizedString(@"str_cloud_disk", @"云盘");
    for (FileInfo *fileInfo in self.fileListArray) {
        fileInfo.selState = NO;
    }
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.coverView removeFromSuperview];
    //self.tableView.mj_header.hidden = NO;
    [self reloadCloudData];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.fileListArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CloudTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    FileInfo *fileInfo = [self.fileListArray objectAtIndex:indexPath.row];
    if (cell == nil) {
        cell = [[CloudTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.detailLable.textColor  = [Utils colorWithKey:@"detailLableColor"];
    cell.fileInfo = fileInfo;
    cell.lineView.backgroundColor = [Utils colorWithKey:@"mainLineColor"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FileInfo *fileInfo = [self.fileListArray objectAtIndex:indexPath.row];
    if (fileInfo.selState == NO) {
        if (![[DocManager getInstance]isDocumentSupported:fileInfo.fileName]) {
            NSString *suffix = [StringUtil getSuffix:fileInfo.fileName];
            [[UIApplication sharedApplication].delegate.window makeToast:[NSString stringWithFormat:NSLocalizedString(@"str_notSupportTheFormatFile:%@", @"暂不支持查看该格式文件"),suffix]];
            return;
        }
        if ([[InboxManager getInstance]isLocalFileExist:fileInfo.fileName]) {
            [self browserFile:fileInfo];
            
        }else{
            [self downloadFile:fileInfo];
        }
        
    }else{
        fileInfo.selected = !fileInfo.selected;
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
    }
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    FileInfo *fileInfo = [self.fileListArray objectAtIndex:indexPath.row];
    NSString *userGuid = [[UserDefaultsUtil shareInstance]getString:LC_USERGUID];
    if ([StringUtil isEmpty:userGuid]) {
        return nil;
    }
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        //粉碎本地文件
        [FileUtil deleteFileWithfilePath:fileInfo.localPath];
        //删除控制台文件
        NSString *url = [ApiSupport getDeleteFileUrl];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"userGUID"] = userGuid;
        params[@"action"] = @"delete";
        params[@"fileNames"] = [StringUtil getFileName:fileInfo.fileName];
        [HttpUtil postWithUrl:url withDict:params withType:@"argv"];
        [self loadFileInfo];
    }];
    deleteAction.backgroundColor = [Utils UIColorFromHex:0XEB4743];
    
    UITableViewRowAction *crushAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"粉碎" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        //粉碎本地文件
        
        [FileUtil deleteFileWithfilePath:fileInfo.localPath];
        [self loadFileInfo];
        
    }];
    crushAction.backgroundColor = [Utils UIColorFromHex:0X7a8ebd];
    NSArray *arr = @[deleteAction,crushAction];
    return arr;
}

#pragma mark - 粉碎操作
- (void)crushHandler:(UIButton *)sender{
    NSInteger count = 0;
    for (FileInfo *fileInfo in self.fileListArray) {
        if (fileInfo.selected) {
            count++;
            break;
        }
        
    }
    if (count != 0) {
        [self showDialog:sender];
    }else{
         NSString * titleStr = [NSString string];
        if ([sender isEqual:_mBtnDelete])
        {
            titleStr = @"str_selectOneFileDeletedAtLeast";
        }else{
            titleStr = @"str_selectOneFileCrushAtLeast";
        }
        [[UIApplication sharedApplication].delegate.window makeToast:NSLocalizedString(titleStr, @"请至少选择一个需要删除的文件")];
    }
}
- (void)showDialog:(UIButton *)sender{
    NSString * titleStr = [NSString string];
    if ([sender isEqual:_mBtnDelete])
    {
        titleStr = @"str_deleteSelectedFiles";
    }else{
        titleStr = @"str_crushSelectedFiles";
    }
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:NSLocalizedString(titleStr, @"删除所选的文件")  message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:NSLocalizedString(@"str_ok", @"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSMutableString *fileNames = [NSMutableString string];
        for (FileInfo *fileInfo in self.fileListArray) {
            if (fileInfo.selected) {
                [fileNames appendString:[StringUtil getFileName:fileInfo.fileName]];
                [fileNames appendString:@","];
                
                if (fileInfo.localExist) {
                    
                    [FileUtil deleteFileWithfilePath:fileInfo.localPath];
                }
            }
        }
        if ([sender isEqual:_mBtnDelete]) {
            if (fileNames.length != 0) {
                //删除控制台文件
                 NSString *userGuid = [[UserDefaultsUtil shareInstance]getString:LC_USERGUID];
                NSString *url = [ApiSupport getDeleteFileUrl];
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                params[@"userGUID"] = userGuid;
                params[@"action"] = @"delete";
                params[@"fileNames"] = fileNames;
                [HttpUtil postWithUrl:url withDict:params withType:@"argv"];
            }
        }
        [self loadFileInfo];
        [self cancelBarButtonItemHnadler];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"str_cancel", @"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVc addAction:confirm];
    [alertVc addAction:cancel];
    [self.navigationController presentViewController:alertVc animated:YES completion:nil];
}
#pragma mark - 文件下载
- (void)downloadFile:(FileInfo *)fileInfo{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showWithStatus:NSLocalizedString(@"str_pleaseWaitForOperationIsCompleted...", "请等待操作完成...")];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if ([fileInfo download]) {
            [SVProgressHUD dismiss];
            [fileInfo updateState];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self reloadCloudData];
                [self browserFile:fileInfo];
            });
        }else{
            [SVProgressHUD dismiss];
        }
    });
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (![DeviceTypeJudge isPadDeviceType]) {
        return 62*KHeightScale;
    }
    return 80;
}

#pragma mark - 浏览文件
- (void)browserFile:(FileInfo *)fileInfo{
    NSString * suffix =  [StringUtil getSuffix:fileInfo.fileName];
    if([suffix containsString:@"dwg"]||[suffix containsString:@"dwt"]||[suffix containsString:@"dxf"]||[suffix containsString:@"dws"]){
        // 当前视窗大小
        CGRect rc = self.view.frame;
        //        // 导航条高度
        CGFloat dNavHeight =  44 + 20;
        //        //如果视图被导航条挡住，需要将显示试图下移
        rc.origin.y = 0;
        rc.size.height += dNavHeight;
        self.navigationController.navigationItem.rightBarButtonItem = nil;
        [UIAlertController exchangeMethod];
        //判断是否打开了水印策略，添加水印效果
        if ([[UserDefaultsUtil shareInstance] getBool:LC_OPENWATERMARKPOLICY]) {
            for (int i = 0; i < 3; i++) {
                UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(20, i * (WINDOWHEIGHT - 250)/2 +60, 250, 80)];
                label.tag = 10000+i;
                label.font = [UIFont systemFontOfSize:16];
                label.textColor = [UIColor grayColor];
                label.transform = CGAffineTransformMakeRotation(-M_1_PI);
                label.text =  [[UserDefaultsUtil shareInstance]getString:LC_WATRMARKTEXT];
                UIWindow * window =   [UIApplication sharedApplication].keyWindow;
                [window addSubview:label];
            }
        }
        //显示图纸浏览视图
        [CADViewer PushCADViewerEx:fileInfo.localPath DocName:@"云盘" NavControl:self.navigationController frameView:rc];
        return;
    }
    
    UIViewController *vc = [[DocManager getInstance]getControllerForFilePath:fileInfo.localPath];
    [self.navigationController pushViewController:vc animated:YES];
}


/**
 *  肤色切换
 */

- (void)skinSwitchHandler{
    [self.tableView reloadData];
    self.tabBarItem.selectedImage = [[Utils imageWithKey:@"tabBar_cloudDisk_click_icon"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.view.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    self.coverView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    [self.mBtnCrush setImage:[[Utils imageWithKey:@"other_icon_crush"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] forState:UIControlStateNormal];
    [self.mBtnDelete setImage:[[Utils imageWithKey:@"other_icon_delete"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] forState:UIControlStateNormal];
    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
